//
//  LoginViewController.m
//  SpendFunk
//
//  Created by bm on 4/18/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "SpendFunkAppDelegate.h"
#import "Global.h"
#import "image.h"

@implementation LoginViewController

@synthesize m_pWebData;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
-(id)init{
	isLogin = true;
	isContinueParse = true;
	return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	
	[self initView];
	
}

-(void)initView{
	////	
	NSString *path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	UIImage *img = [UIImage imageNamed:path];
	UIImageView *imgvBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
	[imgvBar setImage:img];
	[self.view addSubview:imgvBar];
	[imgvBar setUserInteractionEnabled:YES];
	[imgvBar release];
	
	// Background for it
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 45, img.size.width, img.size.height)];
	[imgvBkgr setImage:img];
	[self.view addSubview:imgvBkgr];
	[imgvBkgr setUserInteractionEnabled:YES];
	[imgvBkgr release];
	//back	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];	
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onClickBack) forControlEvents:UIControlEventTouchUpInside];
	[imgvBar addSubview:m_pBtnBack];
	///done
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_NEXT];
	img = [UIImage imageNamed:path];	
	m_pBtnDone = [[UIButton alloc] initWithFrame:CGRectMake(320-5-img.size.width, 5, img.size.width, img.size.height)];
	[m_pBtnDone setBackgroundImage:img forState:UIControlStateNormal];	
	[m_pBtnDone setBackgroundColor:[UIColor clearColor]];
	[m_pBtnDone setTitle:@"Done" forState:UIControlStateNormal];
	[m_pBtnDone addTarget:nil action:@selector(onClickDone) forControlEvents:UIControlEventTouchUpInside];
	[imgvBar addSubview:m_pBtnDone];
	/////	
	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_TABLE_BKGR_LOGIN];
	img = [UIImage imageNamed:path];
	UIImageView *imgvTableBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(320/2-img.size.width/2, 45, img.size.width, img.size.height)];
	[imgvTableBkgr setImage:img];
	[self.view addSubview:imgvTableBkgr];
	[imgvTableBkgr setUserInteractionEnabled:YES];
	[imgvTableBkgr release];
	//email
	
	m_ptxtEmail = [[UITextField alloc] initWithFrame:CGRectMake(120, 20, 180, 30)];
	[m_ptxtEmail setFont:[UIFont systemFontOfSize:14]];
	[m_ptxtEmail setTextColor:[UIColor darkGrayColor]];
	[m_ptxtEmail setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
	[m_ptxtEmail setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
	[m_ptxtEmail setAutocorrectionType:UITextAutocorrectionTypeNo];
	[m_ptxtEmail setReturnKeyType:UIReturnKeyNext];
	m_ptxtEmail.delegate = self;
	[m_ptxtEmail becomeFirstResponder];
	[imgvTableBkgr addSubview:m_ptxtEmail];
	//pass	
	
	m_ptxtPass = [[UITextField alloc] initWithFrame:CGRectMake(120, 60, 180, 30)];
	[m_ptxtPass setFont:[UIFont systemFontOfSize:14]];
	[m_ptxtPass setTextColor:[UIColor darkGrayColor]];
	[m_ptxtPass setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
	[m_ptxtPass setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
	[m_ptxtPass setAutocorrectionType:UITextAutocorrectionTypeNo];
	[m_ptxtPass setReturnKeyType:UIReturnKeyNext];
	m_ptxtPass.secureTextEntry = YES;
	m_ptxtPass.delegate = self;
	[imgvTableBkgr addSubview:m_ptxtPass];
	//test
	m_ptxtPass.text = @"12345";
	m_ptxtEmail.text = @"dongmh.dce.hut@gmail.com";
	
	////
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_FORGOTPASSWORD];
	img = [UIImage imageNamed:path];
	
	m_pBtnForgotPassword = [[UIButton alloc] initWithFrame:CGRectMake(320/2-img.size.width/2, 175, img.size.width, img.size.height)];
	[self.view addSubview:m_pBtnForgotPassword ];
	[m_pBtnForgotPassword setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnForgotPassword addTarget:nil action:@selector(onClickForgotPassword) forControlEvents:UIControlEventTouchUpInside];
	[m_pBtnForgotPassword release];
	
	
	// Please wait ... 
	_blockerView = [[[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)] autorelease];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 0.0;
	_blockerView.clipsToBounds = YES;
	if ([_blockerView.layer respondsToSelector: @selector(setCornerRadius:)]) [(id) _blockerView.layer setCornerRadius: 10];
	
	UILabel								*label = [[[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)] autorelease];
	label.text = NSLocalizedString(@"Please Wait…", nil);
	label.backgroundColor = [UIColor clearColor];
	label.textColor = [UIColor whiteColor];
	label.textAlignment = UITextAlignmentCenter;
	label.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label];
	
	UIActivityIndicatorView				*spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite] autorelease];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
	[self.view addSubview: _blockerView];
	[spinner startAnimating];
	
}

-(void)onClickForgotPassword{
	[m_ptxtEmail resignFirstResponder];
	[m_ptxtPass resignFirstResponder];
	_blockerView.alpha = 1.0;
	
	isLogin = false;
	
	NSString *emtyStr = [[NSString alloc] initWithFormat:@""];
	if ([m_ptxtEmail.text isEqualToString:emtyStr]) 
	{
		_blockerView.alpha = 0.0;
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please insert email." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	else 
	{
		NSString *email = m_ptxtEmail.text;
		
		NSString *post = [[NSString alloc] initWithFormat:@"email=%@",email];
		NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
		
		NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/forgot"];
		NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
		[theRequest setHTTPMethod:@"POST"];  
		[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
		[theRequest setHTTPBody:postData];	
		
		NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
		if( theConnection )
		{
			m_pWebData = [[NSMutableData data] retain];
		}
		else
		{
			
		}
	}
}

-(void)setKeyBroadActive{
	[m_ptxtEmail becomeFirstResponder];
}

-(void)onClickBack{
	[g_AppDelegate goBackHome:self.view];
	[m_ptxtPass resignFirstResponder];
	[m_ptxtEmail resignFirstResponder];
}

-(void)onClickDone{
	[m_ptxtPass resignFirstResponder];
	[m_ptxtEmail resignFirstResponder];
	_blockerView.alpha =1.0;
	[self reqestToServer:m_ptxtEmail.text withPassword:m_ptxtPass.text];
}

-(void)reqestToServer:(NSString *)email withPassword:(NSString *)pass{
	isLogin = true;
	
	NSString *emtyStr = [[NSString alloc] initWithFormat:@""];
	if ([email isEqualToString:emtyStr] || [pass isEqualToString:emtyStr]) 
	{
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please insert email and password" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	else 
	{
		NSString *post = [[NSString alloc] initWithFormat:@"email=%@&password=%@",email,pass];
		NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
		
		NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/login"];
		NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
		[theRequest setHTTPMethod:@"POST"];  
		[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
		[theRequest setHTTPBody:postData];	
		
		NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
		if( theConnection )
		{
			m_pWebData = [[NSMutableData data] retain];
		}
		else
		{
			
		}
		
		[self performSelector:@selector(resetAllInfo) withObject:nil afterDelay:0.5];
	}
}


-(void)resetAllInfo{
	[m_ptxtPass resignFirstResponder];
	[m_ptxtEmail resignFirstResponder];
	m_ptxtPass.text = nil;
	m_ptxtEmail.text = nil;
}

#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	_blockerView.alpha = 0.0;
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		NSLog(@"No Errors");
	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	[connection release];
	[m_pWebData release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
	
	if(isLogin)
	{
		if([currentElement isEqualToString:@"status"])
		{
			if(!currentElementValue) 
				currentElementValue = [[NSString alloc] initWithString:string];
			else
				currentElementValue = [string retain];
			
			if([currentElementValue isEqualToString:@"false"])
			{
			}
			else
			{
			}
		}
		//dang nhap khong thanh cong se hien info
		if([currentElement isEqualToString:@"info"])
		{
			_blockerView.alpha =0.0;
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid information" message:@"Please input correct email and password" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			
			[alert release];
		}
		//dang nhap thanh cong se tra ve id
		if([currentElement isEqualToString:@"userid"])
		{
			g_strLoginUserId = [string retain];
			_blockerView.alpha =0.0;
			[g_AppDelegate openFindFriendsByView:self.view];
			//NSLog(@"%i",g_strLoginUserId);
		}
	}
	else
	{
		if([currentElement isEqualToString:@"status"])
		{
			if(!currentElementValue) 
				currentElementValue = [[NSString alloc] initWithString:string];
			else
				currentElementValue = [string retain];
			
			if([currentElementValue isEqualToString:@"false"])
			{
			}
		}
		//neu can co the hien pass cho user
		if([currentElement isEqualToString:@"new_pass"])
		{
			NSLog(@"pass moi la: %@",string);
			_blockerView.alpha =0.0;
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"An email for new pass has been sent to your email" message:@"Please check email" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			
			[alert release];
		}
		
		//neu loi se hien thong bao qua info
		if([currentElement isEqualToString:@"info"])
		{
			_blockerView.alpha =0.0;
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:[NSString stringWithFormat:@"%@", string] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			
			[alert release];
		}
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	NSLog(@"%@",elementName);
	
	[currentElementValue release];
	currentElementValue = nil;
	
}

#pragma mark Event touch screen
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
	NSLog(@"Touch begin");
	//UITouch *touch = [[event allTouches] anyObject];
	//CGPoint touchLocation = [touch locationInView:touch.view];  //=> toa do
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch move");
}
- (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
	NSLog(@"Touch end");
	[m_ptxtEmail resignFirstResponder];
	[m_ptxtPass resignFirstResponder];
}
#pragma mark textfield delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
	return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
